/**
 * Copyright &copy; 2012-2016 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
 */
package com.server.modules.sys.web.loan;

import com.server.common.config.Global;
import com.server.common.persistence.Page;
import com.server.common.utils.StringUtils;
import com.server.common.web.BaseController;
import com.server.modules.sys.common.StaticDefine;
import com.server.modules.sys.entity.Dict;
import com.server.modules.sys.entity.account.Account;
import com.server.modules.sys.entity.bank.Bank;
import com.server.modules.sys.entity.loan.CustomPay;
import com.server.modules.sys.entity.loan.Loan;
import com.server.modules.sys.entity.loan.LoanManager;
import com.server.modules.sys.entity.loan.LoanMaterialtypeRe;
import com.server.modules.sys.entity.material.MaterialType;
import com.server.modules.sys.entity.material.MaterialUpload;
import com.server.modules.sys.entity.member.Member;
import com.server.modules.sys.entity.settlement.Settlement;
import com.server.modules.sys.entity.settlement.item.SettlementItem;
import com.server.modules.sys.service.DictService;
import com.server.modules.sys.service.account.AccountService;
import com.server.modules.sys.service.bank.BankService;
import com.server.modules.sys.service.loan.CustomPayService;
import com.server.modules.sys.service.loan.LoanManagerService;
import com.server.modules.sys.service.loan.LoanMaterialtypeReService;
import com.server.modules.sys.service.loan.LoanService;
import com.server.modules.sys.service.material.MaterialTypeService;
import com.server.modules.sys.service.material.MaterialUploadService;
import com.server.modules.sys.service.member.MemberService;
import com.server.modules.sys.service.settlement.SettlementService;
import com.server.modules.sys.utils.AmountUtils;
import com.server.modules.sys.utils.PhoneUtil;
import com.server.modules.sys.utils.date.DateStyle;
import com.server.modules.sys.utils.date.DateUtil;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;

/**
 * 客户申请记录Controller
 * @author 王磊
 * @version 2016-09-19
 */
@Controller
@RequestMapping(value = "${adminPath}/sys/loan/customPay")
public class CustomPayController extends BaseController {

	@Autowired
	private CustomPayService customPayService;
	@Autowired
	private MaterialUploadService materialUploadService;
	@Autowired
	private MemberService memberService;
	@Autowired
	private LoanService loanService;
	@Autowired
	private LoanMaterialtypeReService loanMaterialtypeReService;
	@Autowired
	private MaterialTypeService materialTypeService;
	@Autowired
	private SettlementService settlementService;

	@Autowired
	private AccountService accountService;


    @Autowired
    private DictService dictService;

    @Autowired
    private BankService bankService;

	@Autowired
	private LoanManagerService loanManagerService;
	
	@ModelAttribute
	public CustomPay get(@RequestParam(required=false) String id) {
		CustomPay entity = null;
		if (StringUtils.isNotBlank(id)){
			entity = customPayService.get(id);
		}
		if (entity == null){
			entity = new CustomPay();
		}
		return entity;
	}
	
	@RequiresPermissions("sys:loan:customPay:view")
	@RequestMapping(value = {"list", ""})
	public String list(CustomPay customPay, HttpServletRequest request, HttpServletResponse response, Model model) {
        Page<CustomPay> page = customPayService.findPage(new Page<CustomPay>(request, response), customPay);
        List<CustomPay> list = page.getList();
        for (CustomPay pay : list) {
            System.out.println(pay.getCreateDate());
            String loanid = pay.getLoanid();
            if(StringUtils.isNotBlank(loanid)){
                //产品的客服人员
                List<LoanManager> loanManager = loanManagerService.getByLoanId(loanid);
                if(!CollectionUtils.isEmpty(loanManager)){
                    pay.setLoanManagerName(loanManager.get(0).getUserName());
                }
                //商务人员
                Loan loan = loanService.get(new Loan(loanid));
                if(loan!=null){
                    pay.setLoanBankName( loan.getBankName());
                }
                boolean b = PhoneUtil.checkPhoneNumber(pay.getMemberPhone(), "86");
                if(b){
                    pay.setMemberPhoneGeo(PhoneUtil.getGeo(pay.getMemberPhone(),"86"));
                }
			}
        }
        model.addAttribute("page", page);
		model.addAttribute("customPay", customPay);
		return "modules/sys/loan/customPayList";
	}

	@RequiresPermissions("sys:loan:customPay:view")
	@RequestMapping(value = "form")
	public String form(CustomPay customPay, Model model) {
		model.addAttribute("customPay", customPay);
		return "modules/sys/loan/customPayForm";
	}

	@RequiresPermissions("sys:loan:customPay:edit")
	@RequestMapping(value = "save")
	public String save(CustomPay customPay, Model model, RedirectAttributes redirectAttributes) {
		if (!beanValidator(model, customPay)){
			return form(customPay, model);
		}
		customPayService.save(customPay);
		addMessage(redirectAttributes, "保存客户申请记录成功");
		return "redirect:"+Global.getAdminPath()+"/sys/loan/customPay/?repage";
	}
	
	@RequiresPermissions("sys:loan:customPay:edit")
	@RequestMapping(value = "delete")
	public String delete(CustomPay customPay, RedirectAttributes redirectAttributes) {
		customPayService.delete(customPay);
		addMessage(redirectAttributes, "删除客户申请记录成功");
		return "redirect:"+Global.getAdminPath()+"/sys/loan/customPay/?repage";
	}

	/**
	 * 审核资料清晰度
	 * @param member
	 * @param model
	 * @return
	 */
	@RequiresPermissions("sys:loan:customPay:checkmaterialclear")
	@RequestMapping(value = "checkFormPage")
	public String form(Member member, Model model) {
		String memberId = member.getId();
		MaterialUpload materialUpload=new MaterialUpload();
		materialUpload.setMemberId(memberId);
		List<MaterialUpload> findList = materialUploadService.findList(materialUpload);
		List<MaterialUpload> validList =new ArrayList<>();
		for (MaterialUpload upload : findList) {
			if(!upload.getTypeId().equals("1")){
				validList.add(upload);
			}
		}
		model.addAttribute("muList", validList);
		member = memberService.get(member.getId());
		model.addAttribute("member", member);
		return "modules/sys/loan/checkFormPage";
	}

	/**
	 * 审批贷款
	 * @param member
	 * @param loanId
	 * @param model
	 * @param customPayId
	 * @return
	 */
	@RequiresPermissions("sys:loan:customPay:checkloan")
	@RequestMapping(value = "checkLoanFormPage")
	public String checkLoanFormPage(Member member,String loanId, Model model,String customPayId) {
		model.addAttribute("customPayId", customPayId);
		LoanMaterialtypeRe query=new LoanMaterialtypeRe();
		query.setLoanId(loanId);
		List<LoanMaterialtypeRe> reList = loanMaterialtypeReService.findList(query);
		MaterialUpload materialUpload=new MaterialUpload();
        String memberId = member.getId();
        materialUpload.setMemberId(memberId);
        //所有的资料类型
        List<MaterialType> allTypes = materialTypeService.findList(new MaterialType());
        //贷款所需的资料类型
        List<MaterialType> loanNeedTypes =new ArrayList<>();
        model.addAttribute("list", loanNeedTypes);
        //用户所上传的所有资料
		List<MaterialUpload> memberMus = materialUploadService.findList(materialUpload);
        //从关系表中获取贷款所需要的资料类型
		for (LoanMaterialtypeRe loanMaterialtypeRe : reList) {
			//关系表里面的id
			String materialTypeId = loanMaterialtypeRe.getMaterialTypeId();
			for (MaterialUpload materialUpload1 : memberMus) {
				String parentId = materialUpload1.getParentTypeId();
				if(materialTypeId.equals(parentId)){
                    //标记是所需要的资料
					materialUpload1.setIsLoanNeedMaterial(true);
				}
			}
            for (MaterialType materialType2 : allTypes) {
                String parentId2 = materialType2.getParentId();
                String id = materialType2.getId();
                if(materialTypeId.equals(id)||materialTypeId.equals(parentId2)){
                    loanNeedTypes.add(materialType2);
                }
            }
		}
		//把资料分组
        Map<String, List<MaterialUpload>> groupMap=new LinkedHashMap<>();
        int groupIndex=1;
        Map<String, Integer> typeIndexMap=new HashMap<>();
        for (MaterialUpload materialUpload1 : memberMus) {
            //标记同一组上传资料是否缺失或不清晰
            String groupId = materialUpload1.getGroupId();
            if(groupMap.containsKey(groupId)){
                groupMap.get(groupId).add(materialUpload1);
                materialUpload1.setGroupIndex(groupIndex+"");
            }else{
                List<MaterialUpload> groupMemberMus =new ArrayList<>();
                if(typeIndexMap.containsKey(materialUpload1.getParentTypeId())){
                    Integer index= typeIndexMap.get(materialUpload1.getParentTypeId());
                    index++;
                    groupIndex=index;
                    typeIndexMap.put(materialUpload1.getParentTypeId(),groupIndex);
                }else{
                    groupIndex=1;
                    typeIndexMap.put(materialUpload1.getParentTypeId(),groupIndex);
                }
                groupMemberMus.add(materialUpload1);
                groupMap.put(groupId,groupMemberMus);
                materialUpload1.setGroupIndex(groupIndex+"");
            }
        }


          //每一组客户上传的资料
        List<String> msgList=new ArrayList<>();
          for(Map.Entry<String, List<MaterialUpload>> entry:groupMap.entrySet()){
              List<MaterialUpload> value = entry.getValue();
              for (MaterialType loanNeedType : loanNeedTypes) {
                  String parentTypeId = value.get(0).getParentTypeId();
                  if(loanNeedType.getParentId().equals(parentTypeId)){
                     // needType.add(loanNeedType);
                      boolean isClear=false;
                      boolean isNotMiss=false;
                      String groupIndex1=value.get(0).getGroupIndex();
                      String parentTypeName=value.get(0).getParentTypeName();
                      for (MaterialUpload upload : value) {
						  //已上传
                          if(upload.getTypeId().equals(loanNeedType.getId())){
                              isNotMiss=true;
                          }
                            if(upload.getTypeId().equals(loanNeedType.getId())&&upload.getIsClear()!=null&&upload.getIsClear()){
                                isClear=true;
                            }
						    if(upload.getTypeId().equals(loanNeedType.getId())&&!loanNeedType.getType().equals("fileselect")){
                              isClear=true;
                          }
                      }
					  if(!isNotMiss){
						  //未上传
						  StringBuilder msg=new StringBuilder(parentTypeName+groupIndex1+"的【"+loanNeedType.getName()+"】未上传");
						  msgList.add(msg.toString());
					  }else if(isNotMiss){
						  //已上传
						  if(!isClear){
							  msgList.add(parentTypeName+groupIndex1+"的【"+loanNeedType.getName()+"】清晰度审核未通过");
						  }
					  }
                  }

              }
           }
        model.addAttribute("msgList", msgList);
        model.addAttribute("groupMap", groupMap);
		
		return "modules/sys/loan/checkLoanFormPage";
	}

	/**
	 * 结算页
	 * @param model
	 * @return
	 */
	@RequiresPermissions("sys:member:member:view")
	@RequestMapping(value = "load/settlementPage")
	public String settlementPage(CustomPay customPay, Model model) {
        String memberid = customPay.getMemberid();
        Member member = memberService.get(new Member(memberid));
        String loanid = customPay.getLoanid();
        Loan loan = loanService.get(new Loan(loanid));
        model.addAttribute("member",member);
        model.addAttribute("loan",loan);
        model.addAttribute("customPay",customPay);
        Account acc=new Account();
        acc.setParent(new Account("0"));
        List<Account> parentAccounts = accountService.findList(acc);
        for (Account parentAccount : parentAccounts) {
            if(parentAccount.getName().equals("收款方式")){
                Account p=new Account();
                p.setParent(parentAccount);
                model.addAttribute("payTypes", accountService.findList(p));
            } else if(parentAccount.getName().equals("扣除项")){
                Account p=new Account();
                p.setParent(parentAccount);
                model.addAttribute("deductTypes", accountService.findList(p));
            }
        }
		Date date=new Date();
		model.addAttribute("currentDate", DateUtil.DateToString(date,"yyyy-MM-dd"));
        return "modules/sys/loan/load/settlementPage";
	}
	/**
	 * 结算页
	 * @param model
	 * @return
	 */
	@RequiresPermissions("sys:member:member:view")
	@RequestMapping(value = "load/viewMemberInfoPage")
	public String viewMemberInfoPage(CustomPay customPay, Model model) {
        String memberid = customPay.getMemberid();
        Member member = memberService.get(memberid);
        model.addAttribute("member",member);
		String memberId=member.getId();
		//查询用户上传的资料
		if(StringUtils.isNotBlank(memberId)/*&&StringUtils.isNotBlank(materialTypeId)*/){
			MaterialUpload query=new MaterialUpload();
			//    query.setTypeId(materialTypeId);
			query.setMemberId(memberId);
			List<MaterialUpload> list = materialUploadService.findList(query);
			Map<String,List<MaterialUpload>> mapTemp=new HashMap<>();
			//给上传资料分组
			for (MaterialUpload materialUpload : list) {
				if(!mapTemp.containsKey(materialUpload.getGroupId())&&!"1".equals(materialUpload.getTypeId())){
					List<MaterialUpload> listTemp =new ArrayList<>();
					listTemp.add(materialUpload);
					mapTemp.put(materialUpload.getGroupId(),listTemp);
				}else if(!"1".equals(materialUpload.getTypeId())){
					mapTemp.get(materialUpload.getGroupId()).add(materialUpload);
				}
			}
			//根据已上传的客户资料反查资料类型
			Map<MaterialType,List<MaterialUpload>> ret=new LinkedHashMap<>();
			for (List<MaterialUpload> materialUploads : mapTemp.values()) {
				String typeId = materialUploads.get(0).getTypeId();
				//获取资料类型
				MaterialType materialType = materialTypeService.get(typeId);
				MaterialType materialTypeParent= materialTypeService.get(materialType.getParentId());
				MaterialType qeury=new MaterialType();
				qeury.setParent(materialTypeParent);
				List<MaterialType> children = materialTypeService.findList(qeury);
				//类型为radiobox或select要去字典表查询对应的值
				for (MaterialType child : children) {
					if(("radiobox".equals(child.getType())||"select".equals(child.getType()))&&StringUtils.isNotBlank(child.getKeyName())){
						String keyName = child.getKeyName();
						Dict dict=new Dict();
						dict.setType(keyName);
						child.setKeyValues(dictService.findList(dict));
					}
				}
				materialTypeParent.setChildren(children);
				ret.put(materialTypeParent,materialUploads);
			}
			//查询所有资料类型
			MaterialType query2=new MaterialType();
			query2.setParent(new MaterialType("0"));
			List<MaterialType> list1 = materialTypeService.findList(query2);
			for (MaterialType materialType : list1) {
				MaterialType qeury=new MaterialType();
				qeury.setParent(materialType);
				List<MaterialType> children = materialTypeService.findList(qeury);
				//类型为radiobox或select要去字典表查询对应的值
				for (MaterialType child : children) {
					if(("radiobox".equals(child.getType())||"select".equals(child.getType()))&&StringUtils.isNotBlank(child.getKeyName())){
						String keyName = child.getKeyName();
						Dict dict=new Dict();
						dict.setType(keyName);
						child.setKeyValues(dictService.findList(dict));
					}
				}
				materialType.setChildren(children);
			}
			model.addAttribute("typeList",list1);
			model.addAttribute("ret",ret);
		}
		//渠道银行
		model.addAttribute("banks",bankService.findList(new Bank()));

		return "modules/sys/loan/load/viewMemberInfoPage";
	}
	
	@RequiresPermissions("sys:loan:customPay:view")
	@RequestMapping(value = {"passLoan"})
	@ResponseBody
	public Object passLoan(String customPayId,String loanLimit) {
		CustomPay customPay = customPayService.get(customPayId);
        try{
            if(customPay!=null){
                customPay.setLoanLimit(AmountUtils.changeY2F(loanLimit));
                return customPayService.checkPassLoan(customPay);
            }
        }catch (Exception e){
			e.printStackTrace();
            return false;
        }

        return false;
	}
	@RequiresPermissions("sys:loan:customPay:view")
	@RequestMapping(value = {"setFinishLoanLimit"})
	@ResponseBody
	public Object setFinishLoanLimit(String customPayId,String finishLoanLimit) {
		CustomPay customPay = customPayService.get(customPayId);
		try{
			if(customPay!=null){
				customPay.setFinishLoanLimit(AmountUtils.changeY2F(finishLoanLimit));
				 customPayService.save(customPay);
                return  true;
			}
		}catch (Exception e){
			e.printStackTrace();
			return false;
		}

		return false;
	}

    @RequiresPermissions("sys:loan:customPay:view")
    @RequestMapping(value = {"pushUnPassMsg"})
    @ResponseBody
    public Object pushUnPassMsg(String customPayId) {
        CustomPay customPay = customPayService.get(customPayId);
        try{
            if(customPay!=null){
                return customPayService.pushUnPassMsg(customPay);
            }
        }catch (Exception e){
            return false;
        }
        return false;
    }

	@RequestMapping(value = "saveApply")
	@ResponseBody
	public Object saveApply(CustomPay customPay, Model model, RedirectAttributes redirectAttributes) {
		//参数校验
		if(StringUtils.isBlank(customPay.getMemberid())||StringUtils.isBlank(customPay.getCustomServiceId())){
			return false;
		}
		try{
            customPay.setOrderFlag("0");//创建时未支付
            customPay.setOrderNum( new Date().getTime() + StringUtils.createOrder(7));
            customPay.setOrigin(StaticDefine.LOAN_CUSTOM_PAY_ORIGIN.PC);// 来源0移动端 1pc端
            customPayService.save(customPay);
            return true;
        }catch (Exception e){
			e.printStackTrace();
            return false;
        }
	}

	@RequiresPermissions("sys:member:member:inputapply")
	@RequestMapping(value = "editApplyPage")
	public String editApplyPage(Member member,	CustomPay customPay, Model model) {
		if(customPay==null){
			return null;
		}
		model.addAttribute("customPay",customPay);
        String loanid = customPay.getLoanid();
        Loan loan = loanService.get(new Loan(loanid));
        model.addAttribute("loan",loan);
        model.addAttribute("member",member);
		String memberId=member.getId();
		//查询用户上传的资料
		if(StringUtils.isNotBlank(memberId)/*&&StringUtils.isNotBlank(materialTypeId)*/){
			MaterialUpload query=new MaterialUpload();
			//    query.setTypeId(materialTypeId);
			query.setMemberId(memberId);
			List<MaterialUpload> list = materialUploadService.findList(query);
			Map<String,List<MaterialUpload>> mapTemp=new HashMap<>();
			//给上传资料分组
			for (MaterialUpload materialUpload : list) {
				if(!mapTemp.containsKey(materialUpload.getGroupId())&&!"1".equals(materialUpload.getTypeId())){
					List<MaterialUpload> listTemp =new ArrayList<>();
					listTemp.add(materialUpload);
					mapTemp.put(materialUpload.getGroupId(),listTemp);
				}else if(!"1".equals(materialUpload.getTypeId())){
					mapTemp.get(materialUpload.getGroupId()).add(materialUpload);
				}
			}
			//根据已上传的客户资料反查资料类型
			Map<MaterialType,List<MaterialUpload>> ret=new LinkedHashMap<>();
			for (List<MaterialUpload> materialUploads : mapTemp.values()) {
				String typeId = materialUploads.get(0).getTypeId();
				//获取资料类型
				MaterialType materialType = materialTypeService.get(typeId);
				MaterialType materialTypeParent= materialTypeService.get(materialType.getParentId());
				MaterialType qeury=new MaterialType();
				qeury.setParent(materialTypeParent);
				List<MaterialType> children = materialTypeService.findList(qeury);
				//类型为radiobox或select要去字典表查询对应的值
				for (MaterialType child : children) {
					if(("radiobox".equals(child.getType())||"select".equals(child.getType()))&&StringUtils.isNotBlank(child.getKeyName())){
						String keyName = child.getKeyName();
						Dict dict=new Dict();
						dict.setType(keyName);
						child.setKeyValues(dictService.findList(dict));
					}
				}
				materialTypeParent.setChildren(children);
				ret.put(materialTypeParent,materialUploads);
			}
			//查询所有资料类型
			MaterialType query2=new MaterialType();
			query2.setParent(new MaterialType("0"));
			List<MaterialType> list1 = materialTypeService.findList(query2);
			for (MaterialType materialType : list1) {
				MaterialType qeury=new MaterialType();
				qeury.setParent(materialType);
				List<MaterialType> children = materialTypeService.findList(qeury);
				//类型为radiobox或select要去字典表查询对应的值
				for (MaterialType child : children) {
					if(("radiobox".equals(child.getType())||"select".equals(child.getType()))&&StringUtils.isNotBlank(child.getKeyName())){
						String keyName = child.getKeyName();
						Dict dict=new Dict();
						dict.setType(keyName);
						child.setKeyValues(dictService.findList(dict));
					}
				}
				materialType.setChildren(children);
			}
			model.addAttribute("typeList",list1);
			model.addAttribute("ret",ret);
		}
		//渠道银行
		model.addAttribute("banks",bankService.findList(new Bank()));
		return "modules/sys/loan/editApply";
	}
	@RequestMapping(value = "editSaveApply")
	@ResponseBody
	public Object editSaveApply(CustomPay customPay, Model model, RedirectAttributes redirectAttributes) {
		//参数校验
		if(StringUtils.isBlank(customPay.getLoanid())||StringUtils.isBlank(customPay.getMemberLoanLimit())||StringUtils.isBlank(customPay.getId())){
			return false;
		}
		try{
			String memberLoanLimit = customPay.getMemberLoanLimit();
			//转化万为分
			double   d   =   Double.parseDouble(memberLoanLimit);
			customPay.setMemberLoanLimit(d*1000000+"");
			customPay.setOrderFlag("0");//创建时未支付
			customPay.setOrderNum( new Date().getTime() + StringUtils.createOrder(7));
			customPay.setOrigin(StaticDefine.LOAN_CUSTOM_PAY_ORIGIN.PC);// 来源0移动端 1pc端
			customPayService.save(customPay);
			return true;
		}catch (Exception e){
			e.printStackTrace();
			return false;
		}
	}

	/**
	 * 设置订金保存
	 * @param customPay
	 * @return
	 */
	@RequiresPermissions("sys:loan:customPay:setpay")
    @RequestMapping(value = "saveServiceCharge")
    @ResponseBody
    public Object saveServiceCharge(CustomPay customPay) {
        //参数校验
        if(StringUtils.isBlank(customPay.getId())){
            return false;
        }
        if(StringUtils.isBlank(customPay.getServiceCharge())){
            return false;
        }
        try{
            String serviceChargey = customPay.getServiceCharge();
            if(serviceChargey.equals("0")){
                customPay.setOrderFlag(StaticDefine.LOAN_CUSTOM_PAY_ORDER_FLAG.WAITTINGCHECK);
            }
            String serviceChargef = AmountUtils.changeY2F(serviceChargey);
            customPay.setServiceCharge(serviceChargef);
            customPayService.save(customPay);
            return true;
        }catch (Exception e){
            return false;
        }
    }

	/**
	 * 设置利率保存
	 * @param customPay
	 * @return
	 */
	@RequiresPermissions("sys:loan:customPay:setrate")
	@RequestMapping(value = "saveRate")
	@ResponseBody
	public Object saveRate(CustomPay customPay) {
		//参数校验
		if(StringUtils.isBlank(customPay.getId())){
			return false;
		}
		if(StringUtils.isBlank(customPay.getRate())){
			return false;
		}
		try{
			customPayService.save(customPay);
			return true;
		}catch (Exception e){
			e.printStackTrace();
			return false;
		}
	}

	/**
	 * 支付订金
	 * @param customPay
	 * @return
	 */
	@RequiresPermissions("sys:loan:customPay:dopay")
    @RequestMapping(value = "payServiceCharge")
    @ResponseBody
    public Object payServiceCharge(CustomPay customPay) {
        //参数校验
        if(StringUtils.isBlank(customPay.getId())){
            return false;
        }
        if(StringUtils.isBlank(customPay.getServiceCharge())){
            return false;
        }
        try{
            return customPayService.payServiceCharge(customPay);
        }catch (Exception e){
			e.printStackTrace();
			return false;
        }
    }
	@RequiresPermissions("sys:loan:customPay:settlementpay")
    @RequestMapping(value = "paySettlement")
    @ResponseBody
    public Object paySettlement(CustomPay customPay,HttpServletRequest request) {
        //参数校验
        if(StringUtils.isBlank(customPay.getId())){
            return false;
        }
        try{
            return customPayService.paySettlement(customPay,request);
        }catch (Exception e){
			e.printStackTrace();
            return false;
        }
    }
	@RequestMapping(value = "pushMsgTest")
	@ResponseBody
	public Object pushMsgTest(CustomPay customPay,HttpServletRequest request) {
		try{
			return customPayService.pushMsgTest();
		}catch (Exception e){
			e.printStackTrace();
			return false;
		}
	}
	@RequiresPermissions("sys:loan:customPay:settlement")
	@RequestMapping(value = "doSettlement")
	@ResponseBody
	public Object doSettlement(Settlement settlement, String  customPayId, String settlementDateStr) throws Exception {
		if(StringUtils.isBlank(customPayId)){
			return false;
		}
		if(StringUtils.isNotBlank(settlementDateStr)){
			Date date = DateUtil.StringToDate(settlementDateStr, DateStyle.YYYY_MM_DD);
			settlement.setSettlementDate(date);
		}else{
			settlement.setSettlementDate(new Date());
		}
		CustomPay customPay= customPayService.get(new CustomPay(customPayId));
		settlement.setRemarks("财务结算");
		settlement.setMemberId(customPay.getMemberid());
		settlement.setOrders(customPay.getOrderNum());
		settlement.setType(StaticDefine.SETTLEMENT_TYPE.SETTLEMENT);
		customPay.setOrderFlag(StaticDefine.LOAN_CUSTOM_PAY_ORDER_FLAG.WATTINGPAYSETTLEMENT);
		customPayService.save(customPay);
		List<SettlementItem> items = settlement.getItems();
		Double amountIn=0d;
		Double amountOut=0d;
		for (SettlementItem item : items) {
			item.setRemarks("财务结算");
			item.setPayFlag(StaticDefine.SETTLEMENT_ITEM_PAY_FLAG.UNPAY);
			String amountStr = item.getAmountStr();
			String type = item.getType();
			if(StaticDefine.SETTLEMENT_ITEM_TYPE.IN.equals(type)){
				amountIn+= Double.parseDouble(amountStr) ;
			}else if(StaticDefine.SETTLEMENT_ITEM_TYPE.OUT.equals(type)){
				amountOut+= Double.parseDouble(amountStr) ;
			}
			item.setAmount(Long.parseLong(AmountUtils.changeY2F(amountStr)));
		}
		settlement.setAmountIn(Long.parseLong(AmountUtils.changeY2F(amountIn+"")) );
		settlement.setAmountOut(Long.parseLong(AmountUtils.changeY2F(amountOut+"")) );
		return settlementService.saveCascade(settlement);
	}

}